<!--课程与题库-在线课程-编辑在线课程-->
<template>
  <div class="form-container">
    <el-card class="box-card">
      <div class="card-header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/teachers/teacherEdit'}">机构等级评价</el-breadcrumb-item>
          <el-breadcrumb-item>添加/编辑机构等级评价</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :model="form"  ref="baseForm" label-width="120px">
        <div class="head-card">
          <!-- 机构名称 -->
          <el-form-item label="机构名称：" prop="user_name" class="required-item">
            <el-input
              v-model="form.evaName"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <!--    Logo-->
          <el-form-item label="Logo：">
            <div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :on-change="changeavart"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.evaLogoimg" :src="form.evaLogoimg" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="upload-tip">展示于列表和详情页。图片小于1M。
              建议上传 3:4 比例（如750x1000px）的JPG/PNG/WebP格式。</div>
          </el-form-item>


          <!-- 讲师介绍 -->
          <el-form-item label="机构介绍：" prop="user_phoneno" >
            <el-input
              v-model="form.evaContent"
              placeholder="请输入"
              clearable
              type="textarea"
              rows="10"
            ></el-input>
          </el-form-item>
        </div>
        <!--表单操作 -->
        <el-form-item>
          <el-button type="primary" :disabled="isButtonDisabled" @click="savePublic">保存</el-button>
<!--          <el-button type="primary" @click="saveTeachers">仅保存</el-button>-->
          <el-button type="primary" @click="teacherCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { uploadres, createpjjgb } from "../../api/InstitutionApi";
export default {
  data() {
    return {
      form: {
        evaName:'', ///机构名称
        evaLogoimg:'', ///Logo的URL
        evaLogoimgCode: '', ///Logo的code
        evaContent: '', ///机构介绍
      },
      base64Data:'', ///图片base64
      evarow:{},
      isEdit: false
    }
  },
  created() {
    // 对于 path: '/detail/:flowId' 的匹配
    this.evarow = this.$route.query.evarow;
    if(this.evarow) {
      this.isEdit = true
      this.selectEva()
    } else {
      this.isEdit = false
    }
    console.log('ed',this.evarow, this.isEdit);

  },
  computed: {
    isButtonDisabled() {
      // return this.form.base.cur_status === 2; // 可以扩展其他条件，如 || this.isLoading
    }
  },
  methods: {
    selectEva() {
      this.form = {
        evacode: this.evarow.pjjgb_code,
        evaName: this.evarow.pjjgb_name, ///机构名称
        evaLogoimg: '', ///Logo的URL
        evaLogoimgCode: this.evarow.pjjgb_img_uri, ///Logo的code
        evaContent: this.evarow.pjjgb_desc, ///机构介绍
      }
    },
    // 保存在线课程
    savePublic() {
      console.log('评价:：', this.form);
      createpjjgb({
        "pjjgbname": this.form.evaName, ///#评价机构名称
        "pjjgbimguri": this.form.evaLogoimgCode,///#评价机构图片uri
        "pjjgbdesc": this.form.evaContent,///#评价机构描述
      }).then(res=> {
        console.log('评价-1',res)
        this.$router.push({
          path: '/levelEvaluation/levelEvaluation',
          query: ''
        });

      })
    },
    // 取消
    teacherCancel() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });
      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/levelEvaluation/levelEvaluation',
        query: ''
      });
    },

    //头像
    // 头像上传
    // 自定义上传方法
    customUpload(params) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc":"课程图片"  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        this.form.evaLogoimgCode = res.data.base_info
      })
    },

    // 上传前将图片转为base64
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          this.form.evaLogoimg = reader.result; // 带前缀的完整Base64，可直接用于<img>显示

          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload()
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },

    changeavart(file){
      console.log('头像：',file);
      this.beforeUpload(file.raw)
    },
    handleAvatarSuccess(res, file) {
      this.evaLogoimg = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //头像结束
  }
}
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
}

.head-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 30px;
}

.card-select {
  padding-left: 40px;
  font-size: 14px;
  margin-bottom: 30px;

}

.form-title {
  font-size: 18px;
  font-weight: bold;
}

.required-item >>> .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>
